package com.cheng.student.controller.servlet;

import com.cheng.student.beans.Administrator;
import com.cheng.student.service.AdministratorServiceImpl;
import com.cheng.student.service.interfaces.AdministratorService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "SuperLoginServlet", value = "/login/SuperLoginServlet")
public class SuperLoginServlet
        extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        //校验
        String checkCode = request.getParameter("checkCode");
        if(checkCode == null|| "".equals(checkCode))
        {
            response.setHeader("loginInformation","checkCodeNull");
//            response.getWriter().write("请输入验证码");
            return;
        }

        String username = request.getParameter("username");
        if(username == null|| "".equals(username))
        {
            response.setHeader("loginInformation","usernameNull");
//            response.getWriter().write("请输入username");
            return;
        }

        String password = request.getParameter("password");
        if(password == null|| "".equals(password))
        {
            response.setHeader("loginInformation","passwordNull");
//            response.getWriter().write("请输入密码");
            return;
        }
        //通过
        //验证码校验
        String verificationCode = (String) request.getSession().getAttribute("verificationCode");
        if(!verificationCode.equals(checkCode))
        {
            response.setHeader("loginInformation","checkCodeWrong");
//            response.getWriter().write("验证码错误，请重新输入");
            return;
        }
        //通过
        AdministratorService service = new AdministratorServiceImpl();
        Administrator administrator = service.administratorLogin(username, password);
        if(administrator == null)
        {
            response.setHeader("loginInformation","permitWrong");
            return;
        }
        request.getSession().setAttribute("power",administrator.getPower());
        request.getSession().setAttribute("administrator",administrator);
        request.getSession().setMaxInactiveInterval(300);

        response.setHeader("loginInformation","loginSuccess");
        response.setHeader("href","/teacQuery.html");
//        response.getWriter().write("登录成功");


    }
}
